package com.sunsy.authserver.constants;

import java.util.Map;

import com.sunsy.authserver.beans.po.UniformUser;
import com.sunsy.authserver.constants.ApiConstants.User;

/**
 * 用户信息工具类
 *
 * @author 孙思远
 * @date 2021/7/19
 */
public class UserContextHolder {

    private static ThreadLocal<Map<String, Object>> threadLocal;

    private UserContextHolder() {
        threadLocal = new ThreadLocal<>();
    }

    /**
     * 单例静态内部类
     */
    public static class SingletonHolder {

        private static final UserContextHolder INSTANCE = new UserContextHolder();
    }

    public static UserContextHolder getInstance() {
        return SingletonHolder.INSTANCE;
    }

    /**
     * 线程设置副本变量
     *
     * @param value
     */
    public void setContext(Map<String, Object> value) {
        threadLocal.set(value);
    }


    /**
     * 线程获取副本变量
     *
     * @return
     */
    public Map<String, Object> getContext() {
        return threadLocal.get();
    }

    /**
     * 线程获取操作用户名称
     *
     * @return
     */
    public String getUserName() {
        if (threadLocal.get() != null) {
            return String.valueOf(threadLocal.get().getOrDefault(User.USER_NAME, ""));
        }
        return "";
    }


    /**
     * 线程获取操作用户名称
     *
     * @return
     */
    public Long getUserId() {
        if (threadLocal.get() != null)
            return (Long) threadLocal.get().getOrDefault(User.USER_ID, null);
        return 0L;
    }

    public String getUserType() {
        return String.valueOf(threadLocal.get().getOrDefault("type", ""));
    }

    /**
     * 清除threadLocal，避免OOM
     */
    public void clear() {
        threadLocal.remove();
    }

}
